<template>
  <div class="app-container">
    <!-- 添加或修改出入库单据对话框 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="仓库" prop="storeId">
        <el-select v-model="form.storeId" placeholder="请选择仓库">
          <el-option
            v-for="dict in storeList"
            :key="dict.id"
            :label="dict.storeName"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="入库时间" prop="busiDate">
        <el-date-picker clearable
                        v-model="form.busiDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择出库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
      </el-form-item>
      <el-form-item prop="item">
        <el-table
          :data="form.item"
          style="width: 100%">
          <el-table-column
            label="序号"
            type="index" width="100">
          </el-table-column>
          <el-table-column
            label="物品"
            prop="goodsName">
          </el-table-column>
          <el-table-column
            label="价格(单位：元)"
            prop="price" align="center">
            <template v-slot="scope">
              <el-form-item :prop="'item.'+scope.$index+'.price'" :rules="rules.price">
              <el-input v-model="scope.row.price" style="width: 80px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            prop="amounts">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.amounts" :min="1"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            label="小计(单位：元)"
            prop="total">
            <template v-slot="scope">
              <span style="width: 100px">
                                {{(scope.row.amounts * scope.row.price)?fun((scope.row.amounts * scope.row.price)):0}}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center">
            <template slot="header" slot-scope="scope">
              <el-button
                size="large"
                @click="addbill(scope.$index, scope.row)">添加明细
              </el-button>
            </template>
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button type="primary" @click="submitForm">确认提交</el-button>
      <el-button @click="cancel">关闭</el-button>
    </div>
    <el-dialog
      title="物品列表"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose">
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="关键字" prop="goodsName">
            <el-input
              v-model="queryParams.goodsName"
              placeholder="请输入物品名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item  label="分类" prop="categoryId">
            <treeselect   style="width: 250px" v-model="form.categoryId" :options="treeData" :normalizer="normalizer" placeholder="请选择分类" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-primary"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['goods:goods:add']"
            >添加物品
            </el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="goodsList" border>
          <el-table-column label="序号" align="center" prop="goodsId"/>
          <el-table-column label="图片" align="center" prop="goodsCover">
            <template slot-scope="scope">
              <el-image
                style="width: 120px; height: 70px"
                :src="scope.row.goodsCover"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="物品名称" align="center" prop="goodsName"/>
          <el-table-column label="品牌" align="center" prop="brand"/>
          <el-table-column label="分类" align="center" prop="categoryId"/>
          <el-table-column label="数量" align="center" prop="amounts">
            <template v-slot="scope">
              {{scope.row.amounts?scope.row.amounts:0}}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="success"
                icon="el-icon-edit"
                @click="addGood(scope.row)"
                :disabled="scope.row.status"
                v-hasPermi="['goods:goods:edit']"
              >选择该物品
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getGoodsList"
        />
        <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listStore} from "@/api/goods/store";
import {outBill} from "@/api/goods/bill";
import {
  listGoodsStore,
} from "@/api/goods/GoodsStore";
import {treeCategoryDate} from "@/api/goods/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Storage.vue",
  components: {Treeselect},
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      treeData:[],
      // 显示搜索条件
      showSearch: true,
      storeList: [],
      goodsList:[],
      queryParams: {
        pageNum: 1,
        pageSize: 6,
        goodsName: null,
        storeId: null,
        categoryId:null
      },
      total: 10,
      form: {
        item: []
      },
      dialogVisible: false,
      // 表单校验
      rules: {
        storeId: [
          {required: true, message: '必须选择仓库', trigger: 'blur'},
        ],
        busiDate: [
          {required: true, message: '请选择日期', trigger: 'blur'},
        ], remark: [
          {required: true, message: '请输入备注', trigger: 'blur'},
        ],
        price:[{
          required: true, message: '价格不能为空', trigger: 'blur'
        },{ pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确额格式,可保留两位小数' }]
      },
      // 遮罩层
      loading: true,
    };
  },
  created() {
    listStore().then(res => {
      this.storeList = res.rows
    })
    this.getGoodsList()
    this.treeList();
  },
  methods: {
    fun(val){
      return Number(val).toFixed(2)
    },
    addbill() {
      this.dialogVisible = true
    },
    handleAdd(){},
    /** 查询物品信息列表 */
    getGoodsList() {
      this.loading = true;
      listGoodsStore(this.queryParams).then(response => {
        let array = [];
        response.rows.map((res)=>{
          array.push(
            Object.assign(res,{status:false},{goodsId:res.id})
          )
          delete res.id
        });
        this.goodsList = array
        console.log(this.goodsList)
        this.total = response.total;
        this.loading = false;
      });
    },
    addGood(row) {
      this.$modal.msgSuccess("添加物品成功");
      row.status = true
      let item = {...row}
      item.amounts = 1
      this.form.item.push(item)
      console.log(this.form.item)
    },
    // 表单重置
    reset() {
      this.form.item = {
        id: null,
        goodsName: null,
        goodsCover: null,
        categoryId: null,
        brand: null,
        spec: null,
        goodsDesc: null
      };
      this.resetForm("form");
    },
    handleQuery(){
      this.queryParams.pageNum = 1;
      this.getGoodsList();
    },
    resetQuery(){
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDelete(row) {
      this.$modal.confirm('是否删除该物品？').then(function() {
        return true;
      }).then(() =>{
        this.form.item.splice(this.form.item.findIndex(item=>item.goodsId===row.goodsId),1)
        this.goodsList.forEach(res=>{
          if(res.goodsId===row.goodsId){
            res.status = false
          }
        })
      })
    },
    handleClose(){
      this.dialogVisible =false
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          outBill(this.form).then(res => {
            this.$modal.msgSuccess("出库成功");
            this.$router.push({path: `/bill`})
          });
        }
      });
    },
    cancel() {
      this.form = {}
      this.$router.push({path: `/bill`})
    },
    /** 搜索框树形图数据转换 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    /** 查询物品分类树形表 */
    treeList() {
      this.loading = true;
      treeCategoryDate().then(response => {
        this.treeData= response.data
        console.log(this.treeData)
        this.loading = false;
      });
    },
  },
}
</script>
